/*
 * @Author: fanjs
 * @Date: 2025-03-19 13:23:15
 * @Description: 新增编辑
 */

import React, { useRef, useState, useEffect } from 'react';
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerBody,
  Button,
  DrawerFooter,
  Tooltip,
  addToast
} from "@heroui/react";
import { EmailItem } from '../types';
import { SvgIcon } from '@/components/SvgIcon'
import ConfigForm from './ConfigForm';
import { createAndUpdateEmailApi } from '@/service/api/email';

interface OperaDrawer {
  onClose: () => void;
  toContent: (row: EmailItem) => void;
  onConnect: (row: EmailItem) => void;
  isOpen: boolean;
  rowData: EmailItem;
  connectedId: string;
}

const OperaDrawer: React.FC<OperaDrawer> = ({ rowData, isOpen, onClose, connectedId, toContent, onConnect }) => {
  const formRef = useRef<any>(null)
  const [isLoading, setIsLoading] = useState(false) // API是否在验证中

  const [isDisabled, setIsDisabled] = useState(false)
  useEffect(() => {
    setIsDisabled(!!connectedId && rowData.id === connectedId)
  }, [connectedId, rowData.id])

  // 创建链接
  const createLink = async () => {
    const formData = await formRef.current?.fetchData()

    if (rowData.id === connectedId) return addToast({
      description: "密钥已校验通过，请勿重复校验",
      color: "secondary",
    })
    if (!formData.pass) return addToast({ title: "请先填写密钥信息" })
    setIsLoading(true)

    try {
      const params = { ...formData }
      const { data: eid }: any = await createAndUpdateEmailApi(params)
      if (!eid) return
      onConnect({ ...formData, id: eid })

      addToast({
        description: '邮箱客户端配置成功',
        color: "secondary",
      })

      // 新增完成关闭弹窗
      if (!rowData.id) onClose()
    } finally {
      setTimeout(() => setIsLoading(false), 700);
    }
  }

  return (
    <Drawer
      hideCloseButton
      backdrop="blur"
      radius='none'
      size='xl'
      classNames={{
        backdrop: "z-40",
        base: "!h-[100dvh] overflow-hidden touch-none"
      }}
      className='z-0'
      isOpen={isOpen}
    >
      <DrawerContent className="overscroll-none">
        <DrawerHeader className="absolute top-0 inset-x-0 z-50 flex flex-row items-center px-2 py-2 border-b border-default-200/40 backdrop-saturate-150 backdrop-blur-lg">
          <Tooltip content="收起弹窗">
            <Button
              isIconOnly
              size="sm"
              variant="light"
              onPress={onClose}
            >
              <SvgIcon icon='ri:arrow-right-double-line' className="text-lg" />
            </Button>
          </Tooltip>
          <span className="text-[16px]">
            {rowData?.id ? '确认链接配置' : '新增邮箱配置'}
          </span>
        </DrawerHeader>

        <DrawerBody className="pt-16 overflow-y-auto overscroll-none -webkit-overflow-scrolling-touch">
          <ConfigForm
            rowData={rowData}
            ref={formRef}
            isLoading={isLoading}
            isDisabled={isDisabled}
          />
        </DrawerBody>

        <DrawerFooter className='flex justify-start border-t border-default-200/40 py-3 px-4 gap-x-3'>
          {isDisabled && <Button color="secondary" onPress={() => toContent(rowData)}>去配置邮件</Button>}
          <Button isDisabled={isDisabled || isLoading} color='secondary' onPress={createLink}>
            {isLoading && <SvgIcon className='text-4' icon="line-md:loading-twotone-loop" />}
            {isDisabled && !isLoading && <SvgIcon icon="line-md:check-all" />}
            {isLoading ? '校验中...' : isDisabled ? '校验成功' : '校验配置'}
          </Button>
          <Button variant="flat" color="secondary" onPress={onClose}>关 闭</Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  );
}

export default OperaDrawer;
